using System;
using System.Collections.Generic;
using System.Text;
using Decav.Gatsb.Mobile;
using System.IO;
using Decav.Gatsb.Application;
using Decav.Reality;

namespace Decav.Gatsb.MobileProviders
{
    public class TmobileMessageParser : IPhoneMessageParser
    {
        #region IPhoneMessageParser Members

        public MobileMessage ParseMailMessage(SmtpMailHeader header, StreamReader messageStream)
        {
            if (header == null)
                throw new ArgumentNullException("header");

            if (messageStream == null)
                throw new ArgumentNullException("messageStream");

            if (header.Sender.ToString().ToLower().EndsWith("@tmail.com"))
            {
                return ParseSidekickMessage(header, messageStream);
            }
            else
            {
                if (header.ContentType.Type.StartsWith("multipart"))
                    return ParseMms(header, messageStream);
                else
                    return ParseSms(header, messageStream);
            }
        }

        private MobileMessage ParseSidekickMessage(SmtpMailHeader header, StreamReader messageStream)
        {
            if (header.ContentType.Type == ContentType.MultipartMixed.Type)
            {
                // sidekick MMS
                MmsMessage message = ParseMms(header, messageStream);
                message.Body = CleanSignature(message.Body);
                return message;
            }
            else
            {
                // sidekick SMS
                MobileMessage message = ParseSms(header, messageStream);
                message.Body = CleanSignature(message.Body);
                return message;
            }
        }

        private string CleanSignature(string body)
        {
            string[] parts = body.Split(new string[] { "--" }, StringSplitOptions.None);
            if (parts.Length == 1)
                return parts[0];

            // If this seems to be more than a signature, leave it.
            if (parts[parts.Length - 1].Length > 30)
                return body;

            return body.Replace(string.Format("--{0}", parts[parts.Length - 1]), string.Empty);
        }

        private MmsMessage ParseMms(SmtpMailHeader header, StreamReader messageStream)
        {
            StringBuilder messageBody = new StringBuilder();
            List<FileAttachment> attachments = new List<FileAttachment>();

            MultipartReader multipartReader = new MultipartReader(messageStream, header.ContentType.Boundry);
            foreach (FileAttachment attachment in multipartReader.Read())
            {
                if (attachment.Type.Type == ContentType.PlainText.Type)
                {
                    messageBody.AppendLine(attachment.ToText());
                }
                else if (attachment.Type.Type != ContentType.ImageJpeg.Type && attachment.Type.Type != ContentType.ImageJpg.Type)
                {
                    // Dont take the tmobile stock photos or the HTML crap.
                    continue;
                }
                else
                {
                    attachments.Add(attachment);
                }
            }

            string sender = header.Sender.ToString().ToLower().Replace("/type=plmn", string.Empty);
            PhoneNumber telNum = new PhoneNumber(sender.Split('@')[0]);

            string message = messageBody.ToString();
            MmsMessage msg = new MmsMessage(header.Recipient, header.Sender, telNum, header.DateReceived, message);
            foreach (FileAttachment attach in attachments)
                msg.Attachments.Add(attach);

            MessageParser.RemoveReplies(msg);
            return msg;
        }

        private MobileMessage ParseSms(SmtpMailHeader header, StreamReader messageStream)
        {
            string message = messageStream.ReadToEnd().Trim();

            string sender = header.Sender.ToString().ToLower().Replace("/type=plmn", string.Empty);
            PhoneNumber telNum = new PhoneNumber(sender.Split('@')[0]);
            SmsMessage msg = new SmsMessage(header.Recipient, header.Sender, telNum, header.DateReceived, message);
            MessageParser.RemoveReplies(msg);
            return msg;
        }
        #endregion
    }
}
